# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

from django.http import Http404
from django.http import HttpResponseRedirect

from models import Url, Relationship, BlogEntry, Entity, Opinion
from forms import UrlForm, LoginForm, BlogEntryForm, OpinionForm

# from django.utils import simplejson
# from django.http import HttpResponse

@login_required
def index(request):
    entities = Entity.objects.all()
    return render_to_response('index.html', {'entities': entities})

@login_required
def user(request, username):
    try:
        _user = User.objects.filter(username = username)[0]
    except IndexError:
        raise Http404
    if _user == request.user:
        isme = True
    else:
        isme = False
    try:
        rel = Relationship.objects.filter(rfrom = request.user, rto = _user)[0]
        isfriend = True
    except:
        isfriend = False
    entities = Entity.objects.filter(user = _user)
    return render_to_response('user.html', {'user' : _user, 'isfriend': isfriend, 'isme': isme, 'entities': entities})

@login_required
def users(request):
    _users = User.objects.all()
    return render_to_response('users.html', {'users': _users})

@login_required
def urls(request, url):
    try:
        my_url = Url.objects.filter(address = url)[0]
    except:
        return HttpResponseRedirect('/addurl/'+url)
    form = OpinionForm({'entity':my_url.id, 'rating': 0, 'comment': ''})
    rating = my_url.rating()
    opinions = Opinion.objects.filter(entity = my_url)
    return render_to_response('url.html', {'url' : my_url, 'opinionform': form, 'opinions': opinions})

@login_required
def friends(request):
    relationships = request.user.friends.all() #добавить select_related
    friends = [rel.rto for rel in relationships]
    return render_to_response('friends.html', {'friends': friends})
#    entries = Entity.objects.filter(user = request.user)

@login_required
def addurl(request, url):
    try:
        my_url = Url.objects.filter(address = url)[0]
        return HttpResponseRedirect('/url/'+url)
    except:
        if request.method=='POST':
            form = UrlForm(request.POST)
            if form.is_valid():
                new_url = form.save(commit=False)
                new_url.user = request.user
                new_url.save()
                return HttpResponseRedirect('/url/'+new_url.address)
        else:
            form = UrlForm({'address': url})
        return render_to_response('addurl.html', {'form': form})

@login_required
def addfriend(request, username):
    friend_to = User.objects.filter(username = username)[0]
    friend_from = request.user
    if request.method == 'POST':
        try:
            rel = Relationship.objects.filter(rfrom = friend_from, rto = friend_to)[0]
        except IndexError:
            rel = Relationship(rfrom = friend_from, rto = friend_to)
            rel.save()
    else:
        try:
            rel = Relationship.objects.filter(rfrom = friend_from, rto = friend_to)[0]
        except IndexError:
            return render_to_response('addfriend.html', {'username' : username})
    return HttpResponseRedirect('/users/'+username)

@login_required
def rmfriend(request, username):
    friend_to = User.objects.filter(username = username)[0]
    friend_from = request.user
    if request.method == 'POST':
        try:
            rel = Relationship.objects.filter(rfrom = friend_from, rto = friend_to)[0]
            rel.delete()
        finally:
            return HttpResponseRedirect('/users/'+username)
    else:
        try:
            rel = Relationship.objects.filter(rfrom = friend_from, rto = friend_to)[0]
            return render_to_response("rmfriend.html", {'username' : username})
        except:
            return HttpResponseRedirect('/users/'+username)

@login_required
def addentry(request):
    if request.method=='POST':
        form = BlogEntryForm(request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.user = request.user
            new_entry.text = new_entry.text.replace("\n", "<br>")
            new_entry.save()
            return HttpResponseRedirect('/entry/'+str(new_entry.id))
    else:
        form = BlogEntryForm()
    return render_to_response('addentry.html', {'form': form})

@login_required
def entry(request, entry_id):
    try:
        entry = BlogEntry.objects.filter(id = entry_id)[0]
    except IndexError:
        raise Http404
    form = OpinionForm({'entity':entry.id, 'rating': 0, 'comment': ''})
    opinions = Opinion.objects.filter(entity = entry)
    return render_to_response('entry.html', {'entry': entry, 'opinionform': form, 'opinions': opinions})

@login_required
def addopinion(request):
    if request.method!='POST':
        raise Http404
    form = OpinionForm(request.POST)
    if form.is_valid():
        new_opinion = form.save(commit=False)
        new_opinion.user = request.user
        new_opinion.save()
    return HttpResponseRedirect(request.META['HTTP_REFERER'])

#@login_required
#def blog(request):
#    pass

def log_in(request):
    logged_in = False
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(username = form.cleaned_data['username'], \
                                password = form.cleaned_data['password'])
            if user is not None:
                logged_in = True
                login(request, user)
                if request.GET['next']:
                    redir = request.GET['next']
                else:
                    redir = '/login/'
                return HttpResponseRedirect(redir)
            else:
                message = "wrong name or password"
    else:
        form = LoginForm()
        if request.user.is_authenticated():
            message = "hello, " + request.user.username
            logged_in = True
        else:
            message = "please log in"
    next = request.GET.get('next', '/')
    return render_to_response('login.html', {'form' : form,
                                             'message': message,
                                             'logged_in': logged_in,
                                             'next': next})
def log_out(request):
    logout(request)
    return HttpResponseRedirect('/login/')
